﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using CID.Domain.Infrastructure;
using CID.Execution.Support.Information;
using CID.Support.BinaryContentConverters;

namespace CID.Execution.Agent.TemplateHandling
{
    class BATTemplateFileWriter
    {
        public string TemplateContent { get; private set; }
        
        public IEnumerable<ParameterValueInfo> ParameterValues { get; private set; }

        public BATTemplateFileWriter(byte[] templateContent, IEnumerable<ParameterValueInfo> parameterValues)
        {
            TemplateContent = new ASCIIBinaryContentConverter().ToString(templateContent);
            ParameterValues = parameterValues;
        }

        public void WriteTo(string filePath)
        {
            using (var batchFileWriter = new StreamWriter(filePath, false, Encoding.ASCII))
            {
                batchFileWriter.WriteLine("@echo off");
                batchFileWriter.WriteLine();

                foreach (var parameterValue in ParameterValues)
                    batchFileWriter.WriteLine(String.Format("SET {0}={1}", parameterValue.ParameterName, SerializeParameterValue(parameterValue)));
                batchFileWriter.WriteLine();

                batchFileWriter.WriteLine(TemplateContent);
                batchFileWriter.WriteLine();

                batchFileWriter.WriteLine("@echo on");

            }
        }

        private static string SerializeParameterValue(ParameterValueInfo parameterValue)
        {
            var result = string.Empty;
            switch (parameterValue.ParameterType)
            {
                case ParameterType.String: result = parameterValue.StringValue; break;
                case ParameterType.Integer: result = ParameterValueSerializer.Serialize(parameterValue.IntegerValue.Value); break;
                case ParameterType.Decimal: result = ParameterValueSerializer.Serialize(parameterValue.DecimalValue.Value); break;
                case ParameterType.Boolean: result = ParameterValueSerializer.Serialize(parameterValue.BooleanValue.Value); break;
                case ParameterType.DateTime: result = ParameterValueSerializer.Serialize(parameterValue.DateTimeValue.Value); break;
                case ParameterType.UniqueIdentifier: result = ParameterValueSerializer.Serialize(parameterValue.UniqueIdentifierValue.Value); break;
                case ParameterType.Xml: result = parameterValue.XmlValue; break;
                default: throw new ArgumentException(String.Format("Type {0} is not supported", parameterValue.ParameterType)); break;
            }
            return result;
        }
    }
}
